import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Modal } from '@arco-design/web-vue';
import { useUserStore } from '@/store';
import { getToken } from '@/utils/auth';

export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);

// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    // 下载文件不拦截
    if (response.config.url?.indexOf('/service-system/system/file/download') !== -1) {
      console.log(response);
      return response.data;
    }
    // 成功直接返回
    if (response.data.code === 20000) {
      return response.data;
    }
    const res = response.data;
    // 登录失效 50008: Illegal token; 50012: Other clients logged in; 99402: Token expired;
    if ([50008, 50012, 99402].includes(res.code) && response.config.url !== '/api/user/info') {
      Modal.error({
        title: '确认登出',
        content: '登录状态过期',
        okText: '重新登录',
        async onOk() {
          const userStore = useUserStore();
          await userStore.logout();
          window.location.reload();
        }
      });
      return Promise.reject(new Error(res.msg || 'Error'));
    }
    // 业务失败
    Message.error({
      content: res.msg || '请求异常,请联系管理员或检查网络',
      duration: 5 * 1000
    });
    return Promise.reject(new Error(res.msg || 'Error'));
  },
  (error) => {
    Message.error({
      content: error.msg || '请求异常,请联系管理员或检查网络',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);
